/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingmen.canting.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mingmen.canting.R;
import com.mingmen.canting.adapter.QueRenlingAdapter;
import com.mingmen.canting.adapter.YiShenHeAdapter;
import com.mingmen.canting.http.MyOkhttp;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.AppConfig;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.CangKuModel;
import com.mingmen.canting.model.ChuKuModel;
import com.mingmen.canting.model.LoginBean;
import com.mingmen.canting.model.QueRenLingQuModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.PinnedHeaderDecoration;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.zhenban.ZhenBanReplaceFragmentActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import okhttp3.Call;
import okhttp3.Response;


/**
 * <p>
 * ListView形式的侧滑菜单，支持横向和竖向的。
 * </p>
 * Created by Yan Zhenjie on 2016/7/27.
 */
public class QueRenLingQuActivity extends Activity implements QueRenlingAdapter.OnitemClick {
    @BindView(R.id.img_return)
    ImageView imgReturn;

    @BindView(R.id.layout_close)
    LinearLayout layoutClose;

    private RecyclerView mRecyclerView;


    private QueRenlingAdapter mAdapter;
    String string;

    String token;
    String applyId;
    List<QueRenLingQuModel.DataBean> dataBeanList = new ArrayList<>();
    @BindView(R.id.btn_submit)
    Button btn_submit;
    JSONObject jsonObject;
    List<String> mysubmit = new ArrayList<>();
    private int resurtResurant = 100;
    @BindView(R.id.text_date)
    TextView text_date;

    @BindView(R.id.text_size)
    TextView text_size;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newquerenlingqu);
//          activity_querenlingqu
        ButterKnife.bind(this);
        token = (String) SharePreferenceUtil.get(this, "token", "");
        applyId = getIntent().getStringExtra("applyId");
        mAdapter = new QueRenlingAdapter(this, dataBeanList);

        // RecyclerView设置相关
        mRecyclerView = (RecyclerView) findViewById(R.id.main_recycler);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        final PinnedHeaderDecoration decoration = new PinnedHeaderDecoration();
        decoration.registerTypePinnedHeader(1, new PinnedHeaderDecoration.PinnedHeaderCreator() {
            @Override
            public boolean create(RecyclerView parent, int adapterPosition) {
                return true;
            }
        });
//        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setAdapter(mAdapter);
        jsonObject = new JSONObject();
        mAdapter.setOnitemClickLintener(this);
        HttpResponse.showShopDetail(token, applyId, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("QueRenLingQuActivityQueRenLingQuActivity", s);
                QueRenLingQuModel queRenLingQuModel = new QueRenLingQuModel();
                queRenLingQuModel = GsonUtil.GsonToBean(s, QueRenLingQuModel.class);
                dataBeanList.addAll(queRenLingQuModel.getData());
                mAdapter.setDataList(dataBeanList);
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                Date date = null;
                try {
                    date = format1.parse(queRenLingQuModel.getTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (dataBeanList.size() == 0) {
                    Toast.makeText(QueRenLingQuActivity.this, "当前无订单信息", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    text_date.setText(queRenLingQuModel.getData().get(0).getLimitDate());
                    text_size.setText(dataBeanList.size() + "");
                    HttpResponse.getCangKuList(token, "1", new StringCallback(QueRenLingQuActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("CangKuListActivityCangKuListActivity", s);
                            CangKuModel cangKuModel = new CangKuModel();

                            cangKuModel = GsonUtil.GsonToBean(s, CangKuModel.class);

                            if (cangKuModel.getData().size() == 0) {
                                Toast.makeText(QueRenLingQuActivity.this, "当前无仓库", Toast.LENGTH_SHORT).show();
                            } else {
                                for (int i = 0; i < dataBeanList.size(); i++) {
                                    dataBeanList.get(i).setCangku(cangKuModel.getData().get(0).getWarehouse());
                                    warehouseId = cangKuModel.getData().get(0).getWarehouseId();
                                }
                                try {
                                    jsonObject.put("warehouseId", warehouseId);
                                    jsonObject.put("detailId", dataBeanList.get(0).getDetailId());
                                    jsonObject.put("amount", dataBeanList.get(0).getApplyAmount());
                                    mysubmit.add(jsonObject.toString());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                mAdapter.notifyDataSetChanged();
                                mAdapter.setDataList(dataBeanList);
                            }

                        }
                    });
                }


            }
        });


    }


    @OnClick({R.id.img_return, R.id.layout_close, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.img_return:
            case R.id.layout_close:

                finish();

                break;
            case R.id.btn_submit:

                Log.d("btn_submitbtn_submit", jsonObject.toString());
                Log.d("mysubmitmysubmit", mysubmit.toString());
                Log.d("ckkckckck", dataBeanList.size() + "");

                if (TextUtils.isEmpty(warehouseId)) {
                    Toast.makeText(this, "请选择仓库", Toast.LENGTH_SHORT).show();
                } else {

                    Log.d("mysubmitmysubmit", mysubmit.toString());
                    HttpResponse.getChukuSubmit(token, applyId, mysubmit.toString(), new StringCallback(this) {
                        //                    HttpResponse.getChukuSubmit(token, applyId, jsonObject.toString(), new StringCallback(this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("CangkuListCangku", s);
                            ChuKuModel chuKuModel = new ChuKuModel();
                            chuKuModel = GsonUtil.GsonToBean(s, ChuKuModel.class);

                            if (chuKuModel.getCode() == 0) {
                                Toast.makeText(QueRenLingQuActivity.this, chuKuModel.getMessage() + "", Toast.LENGTH_SHORT).show();
                                finish();
                            } else if (chuKuModel.getCode() == 500) {
                                Toast.makeText(QueRenLingQuActivity.this, "已经领取,不能重复领取", Toast.LENGTH_SHORT).show();
                                finish();
                            }

                        }
                    });
                }

//
                break;
        }
    }

    String warehouseId, warehouse;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == resurtResurant) {

            warehouseId = data.getStringExtra("warehouseId");
            warehouse = data.getStringExtra("warehouse");
            try {
                Log.d("warehouseIdwarehouseId", warehouseId);
                Log.d("warehousewarehouse", warehouse);
                if (mysubmit.size() > 0) {
                    mysubmit.clear();
                }
                for (int i = 0; i < dataBeanList.size(); i++) {
                    dataBeanList.get(i).setCangku(warehouse);
                    try {
                        jsonObject.put("warehouseId", warehouseId);
                        jsonObject.put("detailId", dataBeanList.get(i).getDetailId());
                        jsonObject.put("amount", dataBeanList.get(i).getApplyAmount());
                        mysubmit.add(jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {

            }

            mAdapter.setDataList(dataBeanList);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(View view, int position, List<QueRenLingQuModel.DataBean> contacts) {
        Intent intent;
        switch (view.getId()) {
            case R.id.text_cangku:
            case R.id.text_submitcangku:
                intent = new Intent(QueRenLingQuActivity.this, CangKuListActivity.class);
                intent.putExtra("applyId", applyId);
                startActivityForResult(intent, resurtResurant);

                break;
        }

    }
}